package mia.beans;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import org.hibernate.Session;

import mia.dao.UserEntityDAO;
import mia.entity.UserEntity;
import mia.util.DigesterUtil;
import mia.util.HibernateManager;

@ManagedBean(name = "userAdminBean")
@RequestScoped
public class UserAdminBean {
	@ManagedProperty("#{userLoginBean.user}")
	private UserEntity user;

	private UserEntity selectedUser = new UserEntity();
	private List<UserEntity> allUsers = UserEntityDAO.searchUsers("", "", "",
			"", "");
	private String password;
	private String password2;
	private String email2 = new String();
	private String adminPassword;
	private Boolean active;
	private Boolean admin;

	public UserEntity getUser() {
		return user;
	}

	public void setUser(UserEntity user) {
		this.user = user;
	}

	public UserEntity getSelectedUser() {
		return selectedUser;
	}

	public void setSelectedUser(UserEntity selectedUser) {
		this.selectedUser = selectedUser;
	}

	public List<UserEntity> getAllUsers() {
		return allUsers;
	}

	public void setAllUsers(List<UserEntity> allUsers) {
		this.allUsers = allUsers;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPassword2() {
		return password2;
	}

	public void setPassword2(String password2) {
		this.password2 = password2;
	}

	public String getEmail2() {
		return email2;
	}

	public void setEmail2(String email2) {
		this.email2 = email2;
	}

	public String getAdminPassword() {
		return adminPassword;
	}

	public void setAdminPassword(String adminPassword) {
		this.adminPassword = adminPassword;
	}

	public Boolean getActive() {
		return active;
	}

	public void setActive(Boolean active) {
		this.active = active;
	}

	public Boolean getAdmin() {
		return admin;
	}

	public void setAdmin(Boolean admin) {
		this.admin = admin;
	}

	public void tryEdit() {
		FacesContext context = FacesContext.getCurrentInstance();
		if (adminPassword.isEmpty()) {
			context.addMessage("adding", new FacesMessage(
					FacesMessage.SEVERITY_ERROR,
					"Hasło edytującego nie może być puste!", ""));
		} else {
			if (DigesterUtil.checkPassword(adminPassword, user.getPassword())) {

				if (password.equals(password2)) {

					if (!selectedUser.getEmail().equals(email2)
							&& !email2.isEmpty()) {
						context.addMessage("change", new FacesMessage(
								FacesMessage.SEVERITY_ERROR,
								"Wpisane adresy e-mail nie są identyczne!", ""));
					} else {
						if (email_validate(selectedUser.getEmail())) {
							String passwordNewEncrypted = "";
							if (!password.isEmpty()) {
								passwordNewEncrypted = DigesterUtil
										.getDigest(password);
								selectedUser.setPassword(passwordNewEncrypted);
							}
							Session session = null;

							session = HibernateManager.getSession();
							session.beginTransaction();
							String wartosc = selectedUser.getLogin();
							try {
								UserEntity u = UserEntityDAO.getUserByLogin(
										session, selectedUser.getLogin());

								if (!u.getEmail().equals(
										selectedUser.getEmail()))
									u.setEmail(selectedUser.getEmail());
								if (!u.getFirstName().equals(
										selectedUser.getFirstName()))
									u.setFirstName(selectedUser.getFirstName());
								if (!u.getLastName().equals(
										selectedUser.getLastName()))
									u.setLastName(selectedUser.getLastName());

								if (!passwordNewEncrypted.isEmpty()
										&& !u.getPassword().equals(
												passwordNewEncrypted))
									u.setPassword(passwordNewEncrypted);

								if (!u.getPhoneNumber().equals(
										selectedUser.getPhoneNumber()))
									u.setPhoneNumber(selectedUser
											.getPhoneNumber());

								if (!u.isActive() == selectedUser.isActive())
									u.setActive(selectedUser.isActive());

								if (!u.isAdmin() == selectedUser.isAdmin())
									u.setAdmin(selectedUser.isAdmin());

								session.save(u);
								session.getTransaction().commit();
								context.addMessage("change", new FacesMessage(
										FacesMessage.SEVERITY_INFO,
										"Dane zostały zmienione!", ""));
								allUsers = UserEntityDAO.searchUsers("", "", "",
										"", "");
							} catch (Exception ex) {
								context.addMessage(
										"change",
										new FacesMessage(
												FacesMessage.SEVERITY_ERROR,
												wartosc
														+ "Wystąpił błąd: spróbuj ponownie",
												""));
								session.getTransaction().rollback();
							} finally {
								session.close();
							}
						} else {
							context.addMessage("change", new FacesMessage(
									FacesMessage.SEVERITY_ERROR,
									"Podano niepoprawne adres e-mail", ""));
						}
					}

				} else {
					context.addMessage("change", new FacesMessage(
							FacesMessage.SEVERITY_ERROR, "Podano różne hasła!",
							""));
				}
			} else {
				context.addMessage("change", new FacesMessage(
						FacesMessage.SEVERITY_ERROR,
						"Hasło administratora nie jest poprawne!", ""));
			}
		}
	}

	private Boolean email_validate(String email) {
		Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
		Matcher m = p.matcher(email);
		if (m.matches())
			return true;
		else
			return false;
	}

}
